/* 
    Squirrel open project
    Copyright (C) 2012  Elias Aran Paul Farhan
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include <squirrel/sdlengine.hpp>
SDL_Engine::SDL_Engine() : Engine()
{

	//add game and menu
	SDL_Init( SDL_INIT_EVERYTHING );
	SDL_VideoInfo* video_info = (SDL_VideoInfo*) SDL_GetVideoInfo();
	screen_size = std::make_pair(video_info->current_w, video_info->current_h);
	std::cout<<'('<<screen_size.first<<", "<<screen_size.second<<')'<<std::endl;
	this->config();
}
SDL_Engine::~SDL_Engine()
{
	
}

int SDL_Engine::config()
{
	screen_size = std::make_pair(600, 400);
	
	this->screen = SDL_SetVideoMode(this->screen_size.first, this->screen_size.second, 0, SDL_HWSURFACE | SDL_OPENGL | SDL_DOUBLEBUF);// | SDL_FULLSCREEN );
	SDL_EnableUNICODE(1);
	this->game->setScreenSize(screen_size);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_WM_SetCaption( "Squirrel", NULL );
	glEnable(GL_TEXTURE_2D);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
	return 0;
}
int SDL_Engine::run()
{
	SDL_Event event;
	game->init("prout");
	int last_frame = 0;
	int frame = 0;
	int fps = 30;
	bool quit = false;
	Uint8 *keystate = SDL_GetKeyState(NULL);
	bool keys[4] = {false};
	while(!quit)
	{
		frame = SDL_GetTicks();
		if ( frame - last_frame > (int)1000/fps)
		{
			last_frame = frame;
			glClear(GL_COLOR_BUFFER_BIT);
			glViewport(0, 0, this->screen_size.first, this->screen_size.second);
			glMatrixMode(GL_PROJECTION);
			glLoadIdentity();
			glOrtho(0, this->screen_size.first , this->screen_size.second , 0 , 1, -1);
			glMatrixMode(GL_MODELVIEW);
			glLoadIdentity();
			
			//update and draw scene here
			game->updateScene();
			game->drawScene();
			
			while( SDL_PollEvent(&event )) 
			{
				switch( event.type ) 
				{
					case SDL_QUIT:
						quit = true;
						break;
					case SDL_KEYDOWN:
						switch (event.key.keysym.sym)
						{
							case SDLK_ESCAPE:
								quit = true;
								break;
							default:
								break;
						}
						break;
					default:
						break;
				}
			}
			keys[0] = keystate[SDLK_d];
			keys[1] = keystate[SDLK_a];
			keys[2] = keystate[SDLK_w];
			keys[3] = keystate[SDLK_s];
			game->manageKey(keys);
			SDL_GL_SwapBuffers();
		} 
		else 
		{
			SDL_Delay( (int)(1000/fps) - ( frame - last_frame));
		}
		}
	SDL_Quit();
	return 0;
}
